home *** CD-ROM | disk | FTP | other *** search
/ isnet Internet / Isnet Internet CD.iso / prog / hiz / 09 / 09.exe / adynware.exe / perl / lib / Safe.pm < prev    next >
Encoding:
Perl POD Document  |  1999-12-28  |  15.0 KB  |  523 lines

  1. package Safe;
  2.  
  3. use 5.003_11;
  4. use strict;
  5. use vars qw($VERSION);
  6.  
  7. $VERSION = "2.06";
  8.  
  9. use Carp;
  10.  
  11. use Opcode 1.01, qw(
  12.     opset opset_to_ops opmask_add
  13.     empty_opset full_opset invert_opset verify_opset
  14.     opdesc opcodes opmask define_optag opset_to_hex
  15. );
  16.  
  17. *ops_to_opset = \&opset;   # Temporary alias for old Penguins
  18.  
  19.  
  20. my $default_root  = 0;
  21. my $default_share = ['*_']; #, '*main::'];
  22.  
  23. sub new {
  24.     my($class, $root, $mask) = @_;
  25.     my $obj = {};
  26.     bless $obj, $class;
  27.  
  28.     if (defined($root)) {
  29.     croak "Can't use \"$root\" as root name"
  30.         if $root =~ /^main\b/ or $root !~ /^\w[:\w]*$/;
  31.     $obj->{Root}  = $root;
  32.     $obj->{Erase} = 0;
  33.     }
  34.     else {
  35.     $obj->{Root}  = "Safe::Root".$default_root++;
  36.     $obj->{Erase} = 1;
  37.     }
  38.  
  39.     croak "Mask parameter to new no longer supported" if defined $mask;
  40.     $obj->permit_only(':default');
  41.  
  42.     $obj->share_from('main', $default_share);
  43.     return $obj;
  44. }
  45.  
  46. sub DESTROY {
  47.     my $obj = shift;
  48.     $obj->erase if $obj->{Erase};
  49. }
  50.  
  51. sub erase {
  52.     my $obj= shift;
  53.     my $pkg = $obj->root();
  54.     my ($stem, $leaf);
  55.  
  56.     no strict 'refs';
  57.     $pkg = "main::$pkg\::";    # expand to full symbol table name
  58.     ($stem, $leaf) = $pkg =~ m/(.*::)(\w+::)$/;
  59.  
  60.     my $stem_symtab = *{$stem}{HASH};
  61.  
  62.  
  63.     delete $stem_symtab->{$leaf};
  64.  
  65.  
  66.     $obj->share_from('main', $default_share);
  67.     1;
  68. }
  69.  
  70.  
  71. sub reinit {
  72.     my $obj= shift;
  73.     $obj->erase;
  74.     $obj->share_redo;
  75. }
  76.  
  77. sub root {
  78.     my $obj = shift;
  79.     croak("Safe root method now read-only") if @_;
  80.     return $obj->{Root};
  81. }
  82.  
  83.  
  84. sub mask {
  85.     my $obj = shift;
  86.     return $obj->{Mask} unless @_;
  87.     $obj->deny_only(@_);
  88. }
  89.  
  90. sub trap   { shift->deny(@_)   }
  91. sub untrap { shift->permit(@_) }
  92.  
  93. sub deny {
  94.     my $obj = shift;
  95.     $obj->{Mask} |= opset(@_);
  96. }
  97. sub deny_only {
  98.     my $obj = shift;
  99.     $obj->{Mask} = opset(@_);
  100. }
  101.  
  102. sub permit {
  103.     my $obj = shift;
  104.     $obj->{Mask} &= invert_opset opset(@_);
  105. }
  106. sub permit_only {
  107.     my $obj = shift;
  108.     $obj->{Mask} = invert_opset opset(@_);
  109. }
  110.  
  111.  
  112. sub dump_mask {
  113.     my $obj = shift;
  114.     print opset_to_hex($obj->{Mask}),"\n";
  115. }
  116.  
  117.  
  118.  
  119. sub share {
  120.     my($obj, @vars) = @_;
  121.     $obj->share_from(scalar(caller), \@vars);
  122. }
  123.  
  124. sub share_from {
  125.     my $obj = shift;
  126.     my $pkg = shift;
  127.     my $vars = shift;
  128.     my $no_record = shift || 0;
  129.     my $root = $obj->root();
  130.     croak("vars not an array ref") unless ref $vars eq 'ARRAY';
  131.     no strict 'refs';
  132.     croak("Package \"$pkg\" does not exist")
  133.     unless keys %{"$pkg\::"};
  134.     my $arg;
  135.     foreach $arg (@$vars) {
  136.     croak("'$arg' not a valid symbol table name")
  137.         unless $arg =~ /^[\$\@%*&]?\w[\w:]*$/
  138.             or $arg =~ /^\$\W$/;
  139.     my ($var, $type);
  140.     $type = $1 if ($var = $arg) =~ s/^(\W)//;
  141.     *{$root."::$var"} = (!$type)       ? \&{$pkg."::$var"}
  142.               : ($type eq '&') ? \&{$pkg."::$var"}
  143.               : ($type eq '$') ? \${$pkg."::$var"}
  144.               : ($type eq '@') ? \@{$pkg."::$var"}
  145.               : ($type eq '%') ? \%{$pkg."::$var"}
  146.               : ($type eq '*') ?  *{$pkg."::$var"}
  147.               : croak(qq(Can't share "$type$var" of unknown type));
  148.     }
  149.     $obj->share_record($pkg, $vars) unless $no_record or !$vars;
  150. }
  151.  
  152. sub share_record {
  153.     my $obj = shift;
  154.     my $pkg = shift;
  155.     my $vars = shift;
  156.     my $shares = \%{$obj->{Shares} ||= {}};
  157.     @{$shares}{@$vars} = ($pkg) x @$vars if @$vars;
  158. }
  159. sub share_redo {
  160.     my $obj = shift;
  161.     my $shares = \%{$obj->{Shares} ||= {}};
  162.     my($var, $pkg);
  163.     while(($var, $pkg) = each %$shares) {
  164.     $obj->share_from($pkg,  [ $var ], 1);
  165.     }
  166. }
  167. sub share_forget {
  168.     delete shift->{Shares};
  169. }
  170.  
  171. sub varglob {
  172.     my ($obj, $var) = @_;
  173.     no strict 'refs';
  174.     return *{$obj->root()."::$var"};
  175. }
  176.  
  177.  
  178. sub reval {
  179.     my ($obj, $expr, $strict) = @_;
  180.     my $root = $obj->{Root};
  181.  
  182.     my $evalcode = sprintf('package %s; sub { eval $expr; }', $root);
  183.     my $evalsub;
  184.  
  185.     if ($strict) { use strict; $evalsub = eval $evalcode; }
  186.     else         {  no strict; $evalsub = eval $evalcode; }
  187.  
  188.     return Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
  189. }
  190.  
  191. sub rdo {
  192.     my ($obj, $file) = @_;
  193.     my $root = $obj->{Root};
  194.  
  195.     my $evalsub = eval
  196.         sprintf('package %s; sub { do $file }', $root);
  197.     return Opcode::_safe_call_sv($root, $obj->{Mask}, $evalsub);
  198. }
  199.  
  200.  
  201. 1;
  202.  
  203. __DATA__
  204.  
  205. =head1 NAME
  206.  
  207. Safe - Compile and execute code in restricted compartments
  208.  
  209. =head1 SYNOPSIS
  210.  
  211.   use Safe;
  212.  
  213.   $compartment = new Safe;
  214.  
  215.   $compartment->permit(qw(time sort :browse));
  216.  
  217.   $result = $compartment->reval($unsafe_code);
  218.  
  219. =head1 DESCRIPTION
  220.  
  221. The Safe extension module allows the creation of compartments
  222. in which perl code can be evaluated. Each compartment has
  223.  
  224. =over 8
  225.  
  226. =item a new namespace
  227.  
  228. The "root" of the namespace (i.e. "main::") is changed to a
  229. different package and code evaluated in the compartment cannot
  230. refer to variables outside this namespace, even with run-time
  231. glob lookups and other tricks.
  232.  
  233. Code which is compiled outside the compartment can choose to place
  234. variables into (or I<share> variables with) the compartment's namespace
  235. and only that data will be visible to code evaluated in the
  236. compartment.
  237.  
  238. By default, the only variables shared with compartments are the
  239. "underscore" variables $_ and @_ (and, technically, the less frequently
  240. used %_, the _ filehandle and so on). This is because otherwise perl
  241. operators which default to $_ will not work and neither will the
  242. assignment of arguments to @_ on subroutine entry.
  243.  
  244. =item an operator mask
  245.  
  246. Each compartment has an associated "operator mask". Recall that
  247. perl code is compiled into an internal format before execution.
  248. Evaluating perl code (e.g. via "eval" or "do 'file'") causes
  249. the code to be compiled into an internal format and then,
  250. provided there was no error in the compilation, executed.
  251. Code evaulated in a compartment compiles subject to the
  252. compartment's operator mask. Attempting to evaulate code in a
  253. compartment which contains a masked operator will cause the
  254. compilation to fail with an error. The code will not be executed.
  255.  
  256. The default operator mask for a newly created compartment is
  257. the ':default' optag.
  258.  
  259. It is important that you read the Opcode(3) module documentation
  260. for more information, especially for detailed definitions of opnames,
  261. optags and opsets.
  262.  
  263. Since it is only at the compilation stage that the operator mask
  264. applies, controlled access to potentially unsafe operations can
  265. be achieved by having a handle to a wrapper subroutine (written
  266. outside the compartment) placed into the compartment. For example,
  267.  
  268.     $cpt = new Safe;
  269.     sub wrapper {
  270.     }
  271.     $cpt->share('&wrapper');
  272.  
  273. =back
  274.  
  275.  
  276. =head1 WARNING
  277.  
  278. The authors make B<no warranty>, implied or otherwise, about the
  279. suitability of this software for safety or security purposes.
  280.  
  281. The authors shall not in any case be liable for special, incidental,
  282. consequential, indirect or other similar damages arising from the use
  283. of this software.
  284.  
  285. Your mileage will vary. If in any doubt B<do not use it>.
  286.  
  287.  
  288. =head2 RECENT CHANGES
  289.  
  290. The interface to the Safe module has changed quite dramatically since
  291. version 1 (as supplied with Perl5.002). Study these pages carefully if
  292. you have code written to use Safe version 1 because you will need to
  293. makes changes.
  294.  
  295.  
  296. =head2 Methods in class Safe
  297.  
  298. To create a new compartment, use
  299.  
  300.     $cpt = new Safe;
  301.  
  302. Optional argument is (NAMESPACE), where NAMESPACE is the root namespace
  303. to use for the compartment (defaults to "Safe::Root0", incremented for
  304. each new compartment).
  305.  
  306. Note that version 1.00 of the Safe module supported a second optional
  307. parameter, MASK.  That functionality has been withdrawn pending deeper
  308. consideration. Use the permit and deny methods described below.
  309.  
  310. The following methods can then be used on the compartment
  311. object returned by the above constructor. The object argument
  312. is implicit in each case.
  313.  
  314.  
  315. =over 8
  316.  
  317. =item permit (OP, ...)
  318.  
  319. Permit the listed operators to be used when compiling code in the
  320. compartment (in I<addition> to any operators already permitted).
  321.  
  322. =item permit_only (OP, ...)
  323.  
  324. Permit I<only> the listed operators to be used when compiling code in
  325. the compartment (I<no> other operators are permitted).
  326.  
  327. =item deny (OP, ...)
  328.  
  329. Deny the listed operators from being used when compiling code in the
  330. compartment (other operators may still be permitted).
  331.  
  332. =item deny_only (OP, ...)
  333.  
  334. Deny I<only> the listed operators from being used when compiling code
  335. in the compartment (I<all> other operators will be permitted).
  336.  
  337. =item trap (OP, ...)
  338.  
  339. =item untrap (OP, ...)
  340.  
  341. The trap and untrap methods are synonyms for deny and permit
  342. respectfully.
  343.  
  344. =item share (NAME, ...)
  345.  
  346. This shares the variable(s) in the argument list with the compartment.
  347. This is almost identical to exporting variables using the L<Exporter(3)>
  348. module.
  349.  
  350. Each NAME must be the B<name> of a variable, typically with the leading
  351. type identifier included. A bareword is treated as a function name.
  352.  
  353. Examples of legal names are '$foo' for a scalar, '@foo' for an
  354. array, '%foo' for a hash, '&foo' or 'foo' for a subroutine and '*foo'
  355. for a glob (i.e.  all symbol table entries associated with "foo",
  356. including scalar, array, hash, sub and filehandle).
  357.  
  358. Each NAME is assumed to be in the calling package. See share_from
  359. for an alternative method (which share uses).
  360.  
  361. =item share_from (PACKAGE, ARRAYREF)
  362.  
  363. This method is similar to share() but allows you to explicitly name the
  364. package that symbols should be shared from. The symbol names (including
  365. type characters) are supplied as an array reference.
  366.  
  367.     $safe->share_from('main', [ '$foo', '%bar', 'func' ]);
  368.  
  369.  
  370. =item varglob (VARNAME)
  371.  
  372. This returns a glob reference for the symbol table entry of VARNAME in
  373. the package of the compartment. VARNAME must be the B<name> of a
  374. variable without any leading type marker. For example,
  375.  
  376.     $cpt = new Safe 'Root';
  377.     $Root::foo = "Hello world";
  378.     ${$cpt->varglob('foo')} = "Hello world";
  379.  
  380.  
  381. =item reval (STRING)
  382.  
  383. This evaluates STRING as perl code inside the compartment.
  384.  
  385. The code can only see the compartment's namespace (as returned by the
  386. B<root> method). The compartment's root package appears to be the
  387. C<main::> package to the code inside the compartment.
  388.  
  389. Any attempt by the code in STRING to use an operator which is not permitted
  390. by the compartment will cause an error (at run-time of the main program
  391. but at compile-time for the code in STRING).  The error is of the form
  392. "%s trapped by operation mask operation...".
  393.  
  394. If an operation is trapped in this way, then the code in STRING will
  395. not be executed. If such a trapped operation occurs or any other
  396. compile-time or return error, then $@ is set to the error message, just
  397. as with an eval().
  398.  
  399. If there is no error, then the method returns the value of the last
  400. expression evaluated, or a return statement may be used, just as with
  401. subroutines and B<eval()>. The context (list or scalar) is determined
  402. by the caller as usual.
  403.  
  404. This behaviour differs from the beta distribution of the Safe extension
  405. where earlier versions of perl made it hard to mimic the return
  406. behaviour of the eval() command and the context was always scalar.
  407.  
  408. Some points to note:
  409.  
  410. If the entereval op is permitted then the code can use eval "..." to
  411. 'hide' code which might use denied ops. This is not a major problem
  412. since when the code tries to execute the eval it will fail because the
  413. opmask is still in effect. However this technique would allow clever,
  414. and possibly harmful, code to 'probe' the boundaries of what is
  415. possible.
  416.  
  417. Any string eval which is executed by code executing in a compartment,
  418. or by code called from code executing in a compartment, will be eval'd
  419. in the namespace of the compartment. This is potentially a serious
  420. problem.
  421.  
  422. Consider a function foo() in package pkg compiled outside a compartment
  423. but shared with it. Assume the compartment has a root package called
  424. 'Root'. If foo() contains an eval statement like eval '$foo = 1' then,
  425. normally, $pkg::foo will be set to 1.  If foo() is called from the
  426. compartment (by whatever means) then instead of setting $pkg::foo, the
  427. eval will actually set $Root::pkg::foo.
  428.  
  429. This can easily be demonstrated by using a module, such as the Socket
  430. module, which uses eval "..." as part of an AUTOLOAD function. You can
  431. 'use' the module outside the compartment and share an (autoloaded)
  432. function with the compartment. If an autoload is triggered by code in
  433. the compartment, or by any code anywhere that is called by any means
  434. from the compartment, then the eval in the Socket module's AUTOLOAD
  435. function happens in the namespace of the compartment. Any variables
  436. created or used by the eval'd code are now under the control of
  437. the code in the compartment.
  438.  
  439. A similar effect applies to I<all> runtime symbol lookups in code
  440. called from a compartment but not compiled within it.
  441.  
  442.  
  443.  
  444. =item rdo (FILENAME)
  445.  
  446. This evaluates the contents of file FILENAME inside the compartment.
  447. See above documentation on the B<reval> method for further details.
  448.  
  449. =item root (NAMESPACE)
  450.  
  451. This method returns the name of the package that is the root of the
  452. compartment's namespace.
  453.  
  454. Note that this behaviour differs from version 1.00 of the Safe module
  455. where the root module could be used to change the namespace. That
  456. functionality has been withdrawn pending deeper consideration.
  457.  
  458. =item mask (MASK)
  459.  
  460. This is a get-or-set method for the compartment's operator mask.
  461.  
  462. With no MASK argument present, it returns the current operator mask of
  463. the compartment.
  464.  
  465. With the MASK argument present, it sets the operator mask for the
  466. compartment (equivalent to calling the deny_only method).
  467.  
  468. =back
  469.  
  470.  
  471. =head2 Some Safety Issues
  472.  
  473. This section is currently just an outline of some of the things code in
  474. a compartment might do (intentionally or unintentionally) which can
  475. have an effect outside the compartment.
  476.  
  477. =over 8
  478.  
  479. =item Memory
  480.  
  481. Consuming all (or nearly all) available memory.
  482.  
  483. =item CPU
  484.  
  485. Causing infinite loops etc.
  486.  
  487. =item Snooping
  488.  
  489. Copying private information out of your system. Even something as
  490. simple as your user name is of value to others. Much useful information
  491. could be gleaned from your environment variables for example.
  492.  
  493. =item Signals
  494.  
  495. Causing signals (especially SIGFPE and SIGALARM) to affect your process.
  496.  
  497. Setting up a signal handler will need to be carefully considered
  498. and controlled.  What mask is in effect when a signal handler
  499. gets called?  If a user can get an imported function to get an
  500. exception and call the user's signal handler, does that user's
  501. restricted mask get re-instated before the handler is called?
  502. Does an imported handler get called with its original mask or
  503. the user's one?
  504.  
  505. =item State Changes
  506.  
  507. Ops such as chdir obviously effect the process as a whole and not just
  508. the code in the compartment. Ops such as rand and srand have a similar
  509. but more subtle effect.
  510.  
  511. =back
  512.  
  513. =head2 AUTHOR
  514.  
  515. Originally designed and implemented by Malcolm Beattie,
  516. mbeattie@sable.ox.ac.uk.
  517.  
  518. Reworked to use the Opcode module and other changes added by Tim Bunce
  519. E<lt>F<Tim.Bunce@ig.co.uk>E<gt>.
  520.  
  521. =cut
  522.  
  523.